<template>
    <!-- 上架记录 -->
    <div class="p-2">
        <searchrevealing>
            <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="97px">
                <el-form-item label="商品名称" prop="styleName">
                    <el-input v-model="queryParams.styleName" placeholder="请输入" clearable style="width: 220px"
                        @keyup.enter="handleQuery" />
                </el-form-item>

                <el-form-item label="类目" prop="categoryIdList">
                    <el-cascader v-model="queryParams.categoryIdList" :options="options" style="width: 220px" clearable
                        collapse-tags filterable ref="categoryRef" @change="handleChange" placeholder="请选择"
                        :props="props" />
                </el-form-item>

                <el-form-item label="商品编码/69" prop="content">
                    <el-input v-model="queryParams.content" placeholder="请输入" clearable style="width: 220px"
                        @keyup.enter="handleQuery" />
                </el-form-item>

                <el-form-item label="供应商" prop="supplierId">
                    <el-select v-model="queryParams.supplierId" placeholder="请选择供应商" clearable filterable
                        v-selectLoad="selectLoad" :teleported="false" :fit-input-width="true" remote
                        :remote-method="searchQuery" class="supplierSelect" style="width: 220px"
                        :loading="supplierQueryLoading" @clear="handleClear">
                        <el-option v-for="dict in supplierNameOptions" :key="dict.value" :label="dict.label"
                            :value="dict.value">
                        </el-option>
                        <template v-if="supplierLoading">
                            <div class="supplierSelect_icon">
                                <el-icon class="el-select-loading__icon">
                                    <Loading />
                                </el-icon>
                                <span class="el-select-loading__tips">{{ "正在加载" }}</span>
                            </div>
                        </template>
                        <template #loading>
                            <svg class="circular" viewBox="0 0 50 50">
                                <circle class="path" cx="25" cy="25" r="20" fill="none" />
                            </svg>
                        </template>
                    </el-select>
                </el-form-item>


                <el-form-item label="部门类型" prop="recruiterDeptId">
                    <el-select v-model="queryParams.recruiterDeptId" placeholder="请选择部门类型" clearable filterable
                        @change="departmentTypeChange" style="width: 220px">
                        <el-option v-for="dict in departmentTypeList" :key="dict.deptId" :label="dict.deptName"
                            :value="dict.deptId" />
                    </el-select>
                </el-form-item>
                <el-form-item label="部门名称" prop="recruiterDeptIds">
                    <el-select v-model="queryParams.recruiterDeptIds" placeholder="请选择部门名称" clearable filterable
                        @change="deptChange" style="width: 220px">
                        <el-option v-for="dict in deptList" :key="dict.deptId" :label="dict.deptName"
                            :value="dict.deptId" />
                    </el-select>
                </el-form-item>
                <el-form-item label="人员名称" prop="recruiterId">
                    <el-select v-model="queryParams.recruiterId" placeholder="请选择人员名称" clearable filterable
                        style="width: 220px">
                        <el-option v-for="dict in recruiterList" :key="dict.userId" :label="dict.nickName"
                            :value="dict.userId" />
                    </el-select>
                </el-form-item>

                <el-form-item label="库存编码" prop="stockCode">
                    <el-input v-model="queryParams.stockCode" placeholder="请输入" clearable style="width: 220px"
                        @keyup.enter="handleQuery" />
                </el-form-item>

                <el-form-item label="招商入库时间" prop="putTime">
                    <el-date-picker value-format="YYYY-MM-DD" v-model="queryParams.putTime" type="daterange"
                        @change="(e: any) => { pickerChange(e, 'put') }" start-placeholder="开始时间" end-placeholder="结束时间"
                        clearable style="width: 220px" />
                </el-form-item>

                <el-form-item label="招商变价时间" prop="priceTime">
                    <el-date-picker value-format="YYYY-MM-DD" v-model="queryParams.priceTime" type="daterange"
                        @change="(e: any) => { pickerChange(e, 'price') }" start-placeholder="开始时间"
                        end-placeholder="结束时间" clearable style="width: 220px" />
                </el-form-item>

            </el-form>
            <div class="form_button">
                <el-button type="primary" @click="handleQuery" :loading="queryLoading">查询</el-button>
                <el-button @click="resetQuery" :loading="queryLoading">重置</el-button>
            </div>
        </searchrevealing>
        <el-card shadow="never">
            <template #header>
                <!-- <el-col :span="1.5">
                    <el-button type="warning" plain icon="Download" @click="handleExport">导出</el-button>
                </el-col> -->
                <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :name="'产品部变价待接收'"
                    @updateColumn="getColmun"></right-toolbar>
            </template>
            <el-table v-loading="loading" :data="selectionRecordList" border @header-dragend="dragEnd">
                <el-table-column label="序号" type="index" width="55" align="center" :fixed="true" />
                <el-table-column v-for="(item, index) in inventoryRecordColumns" :key="index" :label="item.label"
                    align="center" :prop="item.prop" show-overflow-tooltip :fixed="item.fixed" :width="item.width">
                    <template #default="scope">
                        <image-preview v-if="item.prop == 'productImage'" :src="scope.row.productImage" :width="50"
                            :height="50" />
                        <span v-if="item.prop == 'warehouse'">{{ scope.row.warehouse ? '是' : '否' }}</span>
                        <div v-if="item.prop == 'changeHmMechanismsLists'">
                            <div>{{ computedMechanism(scope.row.changeHmMechanismsLists &&
                                scope.row.changeHmMechanismsLists[0] ||
                                null,
                                '一') }}</div>
                            <div>{{ computedMechanism(scope.row.changeHmMechanismsLists &&
                                scope.row.changeHmMechanismsLists[1] ||
                                null,
                                '二') }}</div>
                            <div>{{ computedMechanism(scope.row.changeHmMechanismsLists &&
                                scope.row.changeHmMechanismsLists[2] ||
                                null,
                                '三') }}</div>
                        </div>
                        <div v-if="item.prop == 'changeHmMechanismsListsOne'">
                            <div>{{ computedMechanism(scope.row.changeHmMechanismsListsOne &&
                                scope.row.changeHmMechanismsListsOne[0] ||
                                null,
                                '一') }}</div>
                            <div>{{ computedMechanism(scope.row.changeHmMechanismsListsOne &&
                                scope.row.changeHmMechanismsListsOne[1] ||
                                null,
                                '二') }}</div>
                            <div>{{ computedMechanism(scope.row.changeHmMechanismsListsOne &&
                                scope.row.changeHmMechanismsListsOne[2] ||
                                null,
                                '三') }}</div>
                        </div>
                        <span v-if="item.prop == 'type'">{{ scope.row.type == 1 ? '研发部' : '招商部' }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right">
                    <template #default="scope">
                        <el-button link type="primary" @click="handleInfo(scope.row)" class="color_theme">详情</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
                v-model:limit="queryParams.pageSize" @pagination="paginationChange" />
        </el-card>
        <!-- 接收 -->
        <commodityHistorydetails type="await" @doClose="commoditymodifyClose"
            :commoditydetailsData="commoditydetailsData" :dialogInfoVisible="dialogInfoVisible">
        </commodityHistorydetails>
    </div>
</template>



<script setup name="StorageRecord" lang="ts">
const { proxy } = getCurrentInstance() as any;
import { getStockList, getCategoryLists, stockAccept } from '@/api/group/productOutbound/index'
import { loginSupplierList } from '@/api/group/supplier/index'
import { getUserList, loginDeptList } from '@/api/group/qualityControl'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getSystemList } from '@/api/group/qualityControl'
import { getPricingById } from '@/api/group/productSelectionPricing'
import commodityHistorydetails from '../historyParticulars.vue'
import { listColumn } from '@/api/system/column';
const inventoryRecordColumns = ref()
const selectionRecordList = ref([]);
const props = { multiple: true }
const loading = ref(true);
const total = ref(0);
const showSearch = ref(true);
const queryFormRef = ref();
const supplierNameOptions = ref<any[]>([])
const columnData = ref()

const deptList = ref<{ deptId: string; deptName: string; }[]>([])
const recruiterList = ref<{ userId: string; nickName: string; }[]>([])

const queryLoading = ref(false)
const supplierNameDate = ref({
    pageNum: 1,
    pageSize: 10,
    supplierName: ''
})
const supplierLoading = ref(true)
const supplierNametotal = ref()
const supplierQueryLoading = ref(false)
const queryParams = ref({
    pageNum: 1,
    pageSize: 10,
    styleName: '',
    content: '',
    supplierId: '',
    recruiterDeptId: undefined,
    recruiterDeptIds: undefined,
    recruiterId: undefined,
    stockCode: '',
    putTime: [],
    inStockStartTime: '',
    inStockEndTime: '',
    priceTime: [],
    requestStartTime: '',
    requestEndTime: '',
    status: '0',
    type: undefined,
    categoryIdList: []
})
const categoryRef = ref();
const options = ref()
const dialogInfoVisible = ref(false)
const commoditydetailsData = ref<any>()
// 部门类型
const departmentTypeList = ref()

onMounted(async () => {
    queryParams.value.pageNum = 1;
    await getColmun();
    await getList();
    getdeptType()
    getCategoryList()
})
/** 查询列表 */
const getList = async () => {
    try {
        loading.value = true;
        const res = await getStockList({ ...queryParams.value, recruiterDeptId: queryParams.value.recruiterDeptIds || queryParams.value.recruiterDeptId });
        selectionRecordList.value = res.rows;
        total.value = res.total;
        loading.value = false;
        queryLoading.value = false
    } catch (e) {
    } finally {
        loading.value = false;
    }
};
/** 页数变化 */
const paginationChange = async () => {
    await getList();
    await proxy?.useColumnUpdate(columnData.value, queryParams.value.pageSize)
    getColmun()
}
/** 获取类目 */
const getCategoryList = async () => {
    try {
        const res = await getCategoryLists();
        const processedData = renameField(res.data);
        options.value = processedData;
    } catch (error) {
        console.error('Failed to get category list:', error);
        options.value = [];
    }
}
// 类目
const renameField = (arr: any[]) => {
    return arr.filter(item => item.categoryStatus === 0).map(element => {
        if (element.children) {
            element.children = renameField(element.children);
        }
        return {
            label: element.categoryName,
            value: element.categoryId,
            ...element,
        };
    });
}
/** select懒加载 */
const selectLoad = async () => {
    if (supplierNameOptions.value.length < supplierNametotal.value) {
        supplierNameDate.value.pageNum++;
        getHmSupplierList()
    }
}
// 获取供应商列表
const getHmSupplierList = async () => {
    supplierLoading.value = true
    const res = await loginSupplierList(supplierNameDate.value)
    const reshandle = res.rows.map((item: any) => (
        {
            label: item.supplierName,
            value: item.id
        }
    ))
    supplierNameOptions.value.push(...reshandle)
    supplierNametotal.value = res.total
    supplierLoading.value = false
}
/** 远程搜索 */
const searchQuery = async (query: string) => {
    supplierQueryLoading.value = true
    supplierNameOptions.value = []
    supplierNameDate.value.pageNum = 1;
    supplierNameDate.value.pageSize = 10
    supplierNameDate.value.supplierName = query
    await getHmSupplierList()
    supplierQueryLoading.value = false
}
/** 清空供应商 */
const handleClear = () => {
    supplierNameDate.value.supplierName = ''
    supplierNameOptions.value = []
    supplierNameDate.value.pageNum = 1;
    supplierNameDate.value.pageSize = 10
    getHmSupplierList()
}

// 获取colmun
const getColmun = async () => {
    const columnDatas = await proxy?.useColumn('产品部变价待接收')
    inventoryRecordColumns.value = columnDatas.columnCustom
    columnData.value = columnDatas
    queryParams.value.pageSize = columnDatas.columnPageSize || 10
}
/** 拖拽事件 */
const dragEnd = async (newWidth: number, oldWidth: number, column: any, event: MouseEvent) => {
    columnData.value.columnCustom.map((item: any) => {
        if (item.prop == column.property) {
            item.width = newWidth
        }
    })
    await proxy?.useColumnUpdate(columnData.value, queryParams.value.pageSize)
}
/** 
 * 获取部门类型
 */
const getdeptType = async () => {
    const res = await getSystemList({ parentId: '1861962988832542721' })
    departmentTypeList.value = res.data
}
/**
 * 部门筛选
 */
const departmentTypeChange = async (parentId: string) => {
    if (parentId) {
        queryParams.value.recruiterDeptIds = undefined
        queryParams.value.recruiterId = undefined
        const res = await getSystemList({ parentId })
        deptList.value = res.data
        recruiterList.value = []
    } else {
        deptList.value = []
        recruiterList.value = []
        queryParams.value.recruiterDeptIds = undefined
        queryParams.value.recruiterId = undefined
    }
}
// 根据招商部获取招商员
const deptChange = async (event: string) => {
    if (event) {
        const res = await getUserList({ deptId: event })
        recruiterList.value = res.rows
        queryParams.value.recruiterId = undefined
    } else {
        recruiterList.value = []
        queryParams.value.recruiterId = undefined
    }
}
// 筛选类目change事件
const handleChange = (val: any) => {

}
/** 完成时间筛选 */
const pickerChange = (val: any, type: string) => {
    if (type === 'put') {
        if (val && val.length) {
            queryParams.value.inStockStartTime = val[0]
            queryParams.value.inStockEndTime = val[1]
        } else {
            queryParams.value.inStockStartTime = ''
            queryParams.value.inStockEndTime = ''
        }
    } else {
        if (val && val.length) {
            queryParams.value.requestStartTime = val[0]
            queryParams.value.requestEndTime = val[1]
        } else {
            queryParams.value.requestStartTime = ''
            queryParams.value.requestEndTime = ''
        }
    }
}
/** 搜索按钮操作 */
const handleQuery = () => {
    queryLoading.value = true
    queryParams.value.pageNum = 1;
    getList();
};
/** 重置按钮操作 */
const resetQuery = () => {
    queryParams.value = {
        pageNum: 1,
        pageSize: 10,
        styleName: '',
        content: '',
        supplierId: '',
        recruiterDeptId: undefined,
        recruiterDeptIds: undefined,
        recruiterId: undefined,
        stockCode: '',
        putTime: [],
        inStockStartTime: '',
        inStockEndTime: '',
        priceTime: [],
        requestStartTime: '',
        requestEndTime: '',
        status: '0',
        type: undefined,
        categoryIdList: []
    }
    deptList.value = []
    recruiterList.value = []
    handleClear();
    handleQuery();
};
// 直播机制
const computedMechanism = (row: any, numbers: string) => {
    if (row) {
        const price = row.price ? row.price : '-'
        const commission = row.commission ? row.commission + '%' : '-'
        const brokerage = row.brokerage ? row.brokerage + '%' : '-'
        const liveStreamingMechanism = row.liveStreamingMechanism ? row.liveStreamingMechanism : '-'
        const costPrice = row.costPrice ? row.costPrice : '-'
        if (row.cooperationMode) {
            if (row.cooperationMode == '分佣') {
                return '机制' + numbers + ': ' + '售价:' + price + ' 佣金:' + commission + ' 补充佣金:' + brokerage + ' 机制:' + liveStreamingMechanism + ' 成本:' + costPrice
            } else {
                return '机制' + numbers + ': ' + '成本:' + costPrice + ' 机制:' + liveStreamingMechanism
            }
        }
    }

}


// 导出按钮操作
const handleExport = () => {
    proxy?.downloadAsync("basic/changeAudit/stockChangeExport", {
        ...queryParams.value,
    }, `待接收记录_${new Date().getTime()}.xlsx`)
}
// 查看商品详情
const handleInfo = (row: any) => {
    nextTick(async () => {
        const res: any = await getPricingById({ id: row.id });
        res.data.changeHmMechanismsListsOne = row.changeHmMechanismsListsOne
        commoditydetailsData.value = res.data
        dialogInfoVisible.value = true;
    });
};
// 去接收关闭
const commoditymodifyClose = () => {
    dialogInfoVisible.value = false;
    getList();
};
</script>
<style lang="scss" scoped>
.mb96 {
    margin-bottom: 96px;
}

:deep(.el-card__header) {
    display: flex;
    justify-content: flex-end;
}

.form_button {
    display: flex;
    justify-content: flex-end;
}

.circular {
    display: inline;
    height: 30px;
    width: 30px;
    animation: loading-rotate 2s linear infinite;
}

.path {
    animation: loading-dash 1.5s ease-in-out infinite;
    stroke-dasharray: 90, 150;
    stroke-dashoffset: 0;
    stroke-width: 2;
    stroke: var(--el-color-primary);
    stroke-linecap: round;
}

.supplierSelect {
    :deep(.el-popper) {
        left: 0 !important;
        top: 34px !important;
        z-index: 7000 !important;
        width: 100% !important;
    }
}

:deep(.el-tabs__content) {
    overflow: visible !important;
}

.supplierSelect_icon {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
}

.el-select-loading__tips {
    color: #606266;
    font-size: 14px;
}
</style>